package com.yang.service;

import com.yang.dao.entity.OnlineTestScore;
import com.yang.dao.entity.OnlineTestStudent;
import com.yang.dao.entity.OnlineTestTopic;
import com.yang.dao.entity.Student;
import com.yang.dao.mapper.OnlineTestScoreMapper;
import com.yang.dao.mapper.OnlineTestStudentMapper;
import com.yang.dao.mapper.OnlineTestTopicMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors;

@Service
public class OnlineTestService {

    @Autowired
    OnlineTestStudentMapper onlineTestStudentMapper;

    @Autowired
    OnlineTestTopicMapper onlineTestTopicMapper;

    @Autowired
    OnlineTestScoreMapper onlineTestScoreMapper;


    @Autowired
    private HttpServletRequest request;
    /**
     * 登录接口
     * @param student
     * @return
     */
   public Integer login(Student student){

       OnlineTestStudent onlineTestStudent = new OnlineTestStudent(student.getId(),student.getName());
       OnlineTestStudent onlineTestStudent1 = onlineTestStudentMapper.selectByNumAndName(onlineTestStudent);
       if(onlineTestStudent1!=null){
           request.getSession().setAttribute("num",onlineTestStudent1.getNum());
            return  1;

       }
       return 0;
   }

    /**
     * 计算分数 并存档
     * @return
     */
    public Integer calculatScore(List<OnlineTestTopic> onlineTestTopics){

        List<OnlineTestTopic> onlineTestTopics1 = onlineTestTopicMapper.selectAll();

        Map<Integer, String> collectMap = onlineTestTopics1.stream().collect(Collectors.toMap(OnlineTestTopic::getNum, OnlineTestTopic::getAnswer));
        AtomicInteger score= new AtomicInteger(0);
        onlineTestTopics.forEach(k->{
            if(collectMap.get(k.getNum()).equalsIgnoreCase(k.getAnswer().trim())){
                score.updateAndGet(v -> v + 1);
            }

        });

        OnlineTestScore onlineTestScore=new OnlineTestScore();

        onlineTestScore.setScore(score.intValue());
        onlineTestScore.setStudentNum((Integer) request.getSession().getAttribute("num"));

        onlineTestScoreMapper.insertSelective(onlineTestScore);

        return  1;
    }


    /**
     * 查询分数
     * @return
     */
    public OnlineTestScore selectScore(){
       return onlineTestScoreMapper.selectByStudentNum((Integer) request.getSession().getAttribute("num"));


    }

}
